import { serviceConfig } from './serviceConfig'
import logUtils from './logUtils/utils'
import Koa from 'koa'
import router from './router'
import cors from 'koa2-cors'
import { catchError } from './catcherror'
import koaStatic from 'koa-static'
import bodyParser from 'koa-bodyparser'
import compress from 'koa-compress'
import './mysql'
const path = require('path')
const app = new Koa()
// 开启gizp
app.use(
  compress({
    threshold: 2048,
  })
)

// 处理跨域
app
  .use(cors())
  .use(bodyParser())
  .use(koaStatic(path.join(__dirname + '/static/')))
  // 增加日志监控
  .use(async (ctx, next) => {
    const start = Date.parse(new Date().toString()) // 响应开始时间
    let intervals // 响应间隔时间
    try {
      await next()
      intervals = Date.parse(new Date().toString()) - start
      logUtils.logResponse(ctx, intervals + '') //记录响应日志
    } catch (error) {
      intervals = Date.parse(new Date().toString()) - start
      logUtils.logError(ctx, error, intervals + '') //记录异常日志
    }
  })
// 添加router
app.use(router.routes()).use(router.allowedMethods())
// 监听全局异常
app.use(catchError)

app.listen(serviceConfig.localhost, () => {
  console.log(`服务已启动: localhost:${serviceConfig.localhost}`)
})
